<template>
  <MainSlot>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :isSelect="true" :tableThead="tableThead" :dataList="dataList" :config="table_config"
        @selection-change="selectionChange">
        <template v-slot:isFreecust="{ row }">
          <span>{{ row.isFreecust ? "是" : "否" }}</span>
        </template>
        <template v-slot:enableStatus="{ row }">
          <span>{{ row.enableStatus ? "是" : "否" }}</span>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" @current-change="handleCurrentChange" :size="pageSize" :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false"  :title="titleText" :visible.sync="dialogFormVisible" @close="cancel('formData')" width="50%">
        <el-form ref="formData" label-position="right" :model="formData" :rules="rules" label-width="100px"
          class="demo-ruleForm">
          <el-form-item label="国家 :" prop="country" disabled>
            <el-input v-model="formData.country" placeholder="请选择" clearable />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="省份 :" prop="province" :rules="[
        { required: true, message: '省份不能为空', trigger: 'blur' },
      ]">
                <el-select class="w100p" v-model="formData.provinceObj" value-key="districtName" clearable filterable
                  default-first-option placeholder="请选择省份" @change="getFlowRegion($event, 1)">
                  <el-option v-for="(item, index) in provinceList" :key="index" :label="item.districtName"
                    :value="{ ...item }" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="城市 :" prop="city" :rules="[
        { required: true, message: '城市不能为空', trigger: 'blur' },
      ]">
                <el-select v-model="formData.cityObj" value-key="districtName" clearable filterable default-first-option
                  placeholder="请选择城市" @change="getFlowRegion($event, 2)">
                  <el-option v-for="(item, index) in cityList" :key="index" :label="item.districtName"
                    :value="{ ...item }" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="县区 :" prop="vsection">
                <el-select v-model="formData.vsection" clearable filterable default-first-option placeholder="请选择县区">
                  <el-option v-for="(item, index) in vsectionList" :key="index" :label="item.districtName"
                    :value="item.districtName" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="grid-content bg-purple"></div>
            </el-col>
          </el-row>



          <el-form-item label="地址详址 :" prop="detailinfo">
            <el-input v-model="formData.detailinfo" type="textarea" placeholder="请输入详细地址" clearable />
          </el-form-item>
          <el-form-item label="邮政编码 :" prop="postcode">
            <el-input v-model="formData.postcode" placeholder="请输入邮政编码" clearable />
          </el-form-item>
          <el-form-item label="备注 :">
            <el-input v-model="formData.remarks" type="textarea" :rows="2" placeholder="请输入备注" clearable />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import BtnSlot from "@/components/BtnSlot";
import TableData from "@/components/TableData";
import { mymixin } from "@/utils/mixins";
import addressApi from "@/api/livestock-manage/inventory/address/addressManage";
import regionApi from "@/api/livestock-manage/inventory/address/region";
import { mapGetters } from "vuex";
export default {
  name: "SheepInformation",
  components: { BtnSlot, Pagination, MainSlot, TableData },
  mixins: [mymixin],
  data() {
    // selectValue 用于传递select的编号
    // isCheck 是否需要单独校验 required是否需要校验 notSearch 是否需要表头搜索
    return {
      selectionList: [],
      tableThead: [],
      btnList: ["add", "delete"],
      selectIndex: 0,
      total: 100,
      currentPage: 1,
      pageSize:10,
      dataList: [],
      SupplierList: [],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "150",
          cols: [
            {
              label: "修改",
              type: "primary",
              flag: "edit",
              handleRow: this.handleRow,
            },
            {
              label: "删除",
              type: "danger",
              flag: "delete",
              handleRow: this.handleRow,
            },
          ],
        },
      },
      // =========================
      selectedStaffList: [],
      provinceList: [],
      cityList: [],
      vsectionList: [],
      districtCode: "",
      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "country",
          typeObj: {},
          name: "国家",
          required: true,
          notSearch: true,
        },
        {
          type: "Select",
          prop: "province",
          selectValue: "districtCode",
          typeObj: {},
          name: "省份",
          required: true,
          notSearch: true,
        },
        {
          type: "Select",
          prop: "city",
          selectValue: "districtCode",
          typeObj: {},
          name: "城市",
          required: true,
          notSearch: true,
        },
        {
          type: "Select",
          prop: "vsection",
          selectValue: "districtCode",
          typeObj: {},
          name: "县区",
          required: true,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "detailinfo",
          typeObj: {},
          name: "详细地址",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "postcode",
          typeObj: {},
          name: "邮政编码",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {},
          name: "备注",
          // required: true,
          notSearch: true,
        },
      ],
      rules: {
        country: [{ required: true, message: "国家不能为空", trigger: "blur" }],
        vsection: [
          { required: true, message: "县区不能为空", trigger: "blur" },
        ],
        detailinfo: [
          { required: true, message: "详细地址不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  created() {
    let list = [];
    this.formDatalists.forEach((el) => {
      let obj = {
        isShow: true,
        label: el.name,
      };
      if (el.prop == "isFreecust") {
        obj.slotName = el.prop;
      } else if (el.prop == "enableStatus") {
        obj.slotName = el.prop;
      } else {
        obj.prop = el.prop;
      }
      list.push(obj);
    });
    this.tableThead = list;
    console.log(this.tableThead);

    this.search();
    this.getProvince();
  },
  methods: {
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.add();
      } else if (flag == "delete") {
        if (this.selectionList.length > 0) {
          this.handleDelete(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
    },
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    handleSizeChange(size){
      this.pageSize = size;
      this.getTableDataList();
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    getFlowRegion(e, a) {
      regionApi.queryAddressByParent(e.districtCode).then((res) => {
        if (res.code === 1) {
          if (a === 1) {
            this.cityList = res.data;
            this.$set(this.formData, "city", "");
            this.$set(this.formData, "vsection", "");
            this.formData.province = e.districtName;
          } else if (a === 2) {
            this.vsectionList = res.data;
            this.$set(this.formData, "vsection", "");
            this.formData.city = e.districtName;
          }
        }
      });
    },
    // 获取省份
    getProvince() {
      regionApi.queryProvinceList().then((res) => {
        if (res.code === 1) {
          this.provinceList = res.data;
          this.$set(this.formDatalists[1], "typeObj", {
            list: res.data,
            listName: ["districtName", "districtCode"],
          });
        }
      });
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == "edit") {
        this.edit({
          ...rowData,
          country: '中国'
        });
      } else if (item.flag == "delete") {
        this.handleDelete([rowData]);
      }
      this.addEditFlag = item.flag;
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: { ...this.searchObj },
      };
      addressApi.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        if (data) {
          console.log(data.content);
          this.dataList = data.content || [];
          this.total = data.totalElements;
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.addressNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      addressApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(list) {
      let selectedStaffList = [];
      list.forEach((item) => {
        selectedStaffList.push(item.addressNo);
      });
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          let params = {
            noList: selectedStaffList,
          };
          addressApi.numberBatchDel(params).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => { });
    },
    add() {
      this.formData = { country: "中国", provinceObj: {}, cityObj: {} };
      this.nowChanceStau = "add";
      this.titleText = "添加地址簿";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      regionApi
        .queryByCondition({ districtName: row.province, level: 1 })
        .then((res) => {
          if (res.code === 1) {
            this.$set(this.formData, "provinceObj", ...res.data);
            regionApi
              .queryAddressByParent(res.data[0].districtCode)
              .then((res) => {
                if (res.code === 1) {
                  this.cityList = res.data;
                }
              });
          }
        });
      regionApi
        .queryByCondition({ districtName: row.city, level: 2 })
        .then((res) => {
          if (res.code === 1) {
            this.$set(this.formData, "cityObj", ...res.data);
            regionApi
              .queryAddressByParent(res.data[0].districtCode)
              .then((res) => {
                if (res.code === 1) {
                  this.vsectionList = res.data;
                }
              });
          }
        });
      this.nowChanceStau = "edit";
      this.titleText = "修改地址簿";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            addressApi.edit(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            addressApi.add(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss"></style>
